﻿using Common.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using WinServiceFileListener.Consts;
using WinServiceFileListener.Extensions;
using WinServiceFileListener.Helpers;

namespace WinServiceFileListener
{
    public partial class FolderListener : ServiceBase
    {
        public FolderListener()
        {
            InitializeComponent();
        }
        
        FileSystemWatcher fsw = new FileSystemWatcher();
        public void StartService(string[] args)
        {
            Program.FolderListenerIniReadWrite();
            OnStart(args);
        }
        protected override void OnStart(string[] args)
        {
            this.WriteLog("服务启动成功！");

            //开启调试需要账号密码，不然别人能看源码
            #region 是否开启调试
            //是否开启调试
            var str = IniConst.IsDebug.Split(' ');
            var isDebug = str[0];
            string user = "";

            if (str.Length > 1)
                user = str[1];

            if (isDebug == "T")
            {
                string author = ConfigurationManager.AppSettings["Author"]?.ToString();
                if (string.IsNullOrWhiteSpace(user))
                {
                    this.WriteLog($"还没输入密码，不能调试");
                }
                else if (user == author)
                {
                    Debugger.Launch();
                }
                else
                {
                    this.WriteLog($"密码不对，请稍后再进行调试");
                }

            }
            #endregion

            try
            {
                #region 监听文件（夹）路径
                string path = IniConst.FolderListenPath;
                if (string.IsNullOrWhiteSpace(path))
                {
                    throw new CustomException("监听路径为空！");
                }
                else if (!Directory.Exists(path))
                {
                    throw new CustomException($"找不到路径：【{path}】");
                }

                //fsw.Path = @"E:\Company\";
                fsw.Path = path;
                fsw.NotifyFilter = NotifyFilters.DirectoryName;
                fsw.IncludeSubdirectories = true;
                fsw.EnableRaisingEvents = true;
                fsw.Created += Fsw_Created;
                fsw.Deleted += Fsw_Deleted;
                fsw.Renamed += Fsw_Renamed;
                fsw.Changed += Fsw_Changed;
                #endregion

                this.WriteLog($"监听路径为：{path}");
            }
            catch (CustomException ex)
            {
                this.WriteLog($"{ex.Message}");
            }
            catch (Exception ex)
            {
                fsw.EnableRaisingEvents = false;//停止监听
                this.WriteLog($"启动服务异常：{ex}");
            }

        }
        

        private void Fsw_Changed(object sender, FileSystemEventArgs e)
        {
            //this.WriteLog("Fsw_Changed");

        }

        private void Fsw_Renamed(object sender, RenamedEventArgs e)
        {
            //this.WriteLog("Fsw_Renamed");
        }

        private void Fsw_Deleted(object sender, FileSystemEventArgs e)
        {
            //this.WriteLog("Fsw_Deleted");
        }

        private void Fsw_Created(object sender, FileSystemEventArgs e)
        {
            string strContains = "";
            string fullPath = e.FullPath;// E:\Company\KrPeSelf\IDCard\bin - 副本
            string listPathKey = IniConst.FolderListenPathKey;
            string filterPathKey = IniConst.FolderFilterPathKey;
            string newPath = "";
            try
            {
                if (e.ChangeType == WatcherChangeTypes.Created)
                {
                    if (!string.IsNullOrEmpty(listPathKey) && !fullPath.IsContains(ref strContains, listPathKey))
                    {
                        //throw new CustomException($"对路径【{fullPath}】命名不生效，因为该路径不在关键字范围内【{strContains}】");
                        return;
                    }

                    if (fullPath.IsContains(ref strContains, IniConst.FolderFilterPathKey))
                    {
                        //throw new CustomException($"对路径【{fullPath}】命名失败，路径不能包含关键字【{strContains}】");
                        return;
                    }

                    string path = Path.GetFileName(fullPath);//获取最深子级的目录名
                    if (!path.IsContains(ref strContains, "新建文件夹"))
                    {
                        //throw new CustomException($"对路径【{fullPath}】命名失败，并不是创建【{strContains}】");
                        return;
                    }
                   
                    string parentDirec = Path.GetDirectoryName(fullPath);// E:\Company\KrPeSelf\IDCard
                    newPath = FolderHelper.CreateDateFolder(parentDirec);// E:\Company\KrPeSelf\IDCard\2024-0906 0852
                    
                    // 重命名文件夹
                    Directory.Move(fullPath, newPath);
                    //SendKeys.Send("{F2}");
                }


            }
            catch (CustomException ex)
            {
                this.WriteLog($"{ex.Message}");
            }
            catch (Exception ex)
            {
                string msg = $"将文件夹【{fullPath}】命名为【{newPath}】异常：";
                this.WriteLog($"{msg}{ex}");
            }

        }
        public void StopService()
        {
            OnStop();
        }
        protected override void OnStop()
        {
            FswStop();
            this.WriteLog("服务停止成功");

        }

        /// <summary>
        /// 停止监听文件是否改动
        /// </summary>
        protected void FswStop()
        {
            if (fsw != null)
            {
                fsw.EnableRaisingEvents = false;
                fsw.Dispose();
            }
        }
    }
}
